# ========================================
# CocoKeyboard Auto APK Builder (Release)
# 3秒自动开始，无需等待
# ========================================

$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "CocoKeyboard Auto Builder (Release)" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

$projectRoot = $PSScriptRoot

# ====================================
# Step 1: Check and setup Java
# ====================================
Write-Host "[1/5] Checking Java environment..." -ForegroundColor Yellow

function Find-JavaHome {
    # Check current JAVA_HOME
    if ($env:JAVA_HOME -and (Test-Path "$env:JAVA_HOME\bin\java.exe")) {
        return $env:JAVA_HOME
    }
    
    # Check common Java installation locations
    $javaLocations = @(
        "${env:ProgramFiles}\Java",
        "${env:ProgramFiles(x86)}\Java",
        "${env:ProgramFiles}\Android\Android Studio\jbr",
        "${env:LOCALAPPDATA}\Programs\Android\Android Studio\jbr",
        "C:\Program Files\Java",
        "C:\Program Files (x86)\Java",
        "C:\Program Files\Android\Android Studio\jbr"
    )
    
    foreach ($location in $javaLocations) {
        if (Test-Path $location) {
            $jdks = Get-ChildItem $location -Directory | Where-Object { 
                $_.Name -match "jdk|jbr" 
            } | Sort-Object Name -Descending
            
            foreach ($jdk in $jdks) {
                $javaExe = Join-Path $jdk.FullName "bin\java.exe"
                if (Test-Path $javaExe) {
                    return $jdk.FullName
                }
            }
        }
    }
    
    return $null
}

$javaHome = Find-JavaHome

if ($javaHome) {
    $env:JAVA_HOME = $javaHome
    $env:PATH = "$javaHome\bin;$env:PATH"
    Write-Host "  Found Java: $javaHome" -ForegroundColor Green
    
    # Test Java version
    try {
        $javaVersion = & "$javaHome\bin\java.exe" -version 2>&1 | Select-Object -First 1
        Write-Host "  $javaVersion" -ForegroundColor Gray
    } catch {
        Write-Host "  Java found but version check failed" -ForegroundColor Yellow
    }
} else {
    Write-Host ""
    Write-Host "[ERROR] Java not found!" -ForegroundColor Red
    Write-Host ""
    Write-Host "Please install Java JDK 11 or higher:" -ForegroundColor Yellow
    Write-Host "  1. Download from: https://adoptium.net/" -ForegroundColor White
    Write-Host "  2. Or install Android Studio (includes Java)" -ForegroundColor White
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Gray
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    exit 1
}

# ====================================
# Step 2: Read version info
# ====================================
Write-Host ""
Write-Host "[2/5] Reading version information..." -ForegroundColor Yellow

$gradlePropsFile = Join-Path $projectRoot "gradle.properties"

$versionName = ""
$versionCode = ""

Get-Content $gradlePropsFile | ForEach-Object {
    if ($_ -match "projectVersionName=(.+)") {
        $versionName = $matches[1].Trim()
    }
    if ($_ -match "projectVersionCode=(.+)") {
        $versionCode = $matches[1].Trim()
    }
}

$buildDate = Get-Date -Format "yyyyMMdd"
$buildTime = Get-Date -Format "HHmmss"
$projectName = "CocoKeyboard"

Write-Host "  Project: $projectName" -ForegroundColor Green
Write-Host "  Version: $versionName (Code: $versionCode)" -ForegroundColor Green
Write-Host "  Date: $buildDate" -ForegroundColor Green

# ====================================
# Step 3: Auto-start countdown
# ====================================
$buildType = "Release"
$gradleTask = "assembleRelease"
$apkPath = Join-Path $projectRoot "app\build\outputs\apk\release"
$apkName = "app-release.apk"  # 已签名的APK
$suffix = "release"

Write-Host ""
Write-Host "[3/5] Auto-building Release version..." -ForegroundColor Yellow
Write-Host ""
Write-Host "  Building Release APK (fully optimized)" -ForegroundColor Cyan
Write-Host "  Press Ctrl+C to cancel..." -ForegroundColor Gray
Write-Host ""

# Countdown
for ($i = 3; $i -gt 0; $i--) {
    Write-Host "  Starting in $i seconds..." -ForegroundColor Yellow -NoNewline
    Start-Sleep -Seconds 1
    Write-Host "`r" -NoNewline
}
Write-Host "  Starting build now!                    " -ForegroundColor Green

# ====================================
# Step 4: Build APK
# ====================================
Write-Host ""
Write-Host "[4/5] Building APK..." -ForegroundColor Yellow
Write-Host ""

Set-Location $projectRoot

if ($IsWindows -or $env:OS -match "Windows") {
    $gradleCmd = ".\gradlew.bat"
} else {
    $gradleCmd = "./gradlew"
}

$startTime = Get-Date

# Clean first (for Release builds)
Write-Host "Cleaning project..." -ForegroundColor Gray
& $gradleCmd clean | Out-Null

Write-Host "Building Release APK (this may take 2-5 minutes)..." -ForegroundColor Gray
Write-Host ""

& $gradleCmd $gradleTask

$endTime = Get-Date
$duration = $endTime - $startTime

if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Red
    Write-Host "[ERROR] Build failed!" -ForegroundColor Red
    Write-Host "========================================" -ForegroundColor Red
    Write-Host ""
    Write-Host "Build time: $($duration.Minutes)m $($duration.Seconds)s" -ForegroundColor Gray
    Write-Host ""
    Write-Host "Common issues:" -ForegroundColor Yellow
    Write-Host "  1. Check if all dependencies are installed" -ForegroundColor White
    Write-Host "  2. Try running: clean-cache.bat" -ForegroundColor White
    Write-Host "  3. Check error messages above" -ForegroundColor White
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Gray
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    exit 1
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "Build successful!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Build time: $($duration.Minutes)m $($duration.Seconds)s" -ForegroundColor Gray

# ====================================
# Step 5: Rename and copy APK
# ====================================
Write-Host ""
Write-Host "[5/5] Processing APK..." -ForegroundColor Yellow

$sourceApk = Join-Path $apkPath $apkName

if (-not (Test-Path $sourceApk)) {
    Write-Host ""
    Write-Host "[ERROR] APK file not found: $sourceApk" -ForegroundColor Red
    Write-Host "Press any key to exit..." -ForegroundColor Gray
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    exit 1
}

# Create output directory
$outputDir = Join-Path $projectRoot "releases"
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}

# Generate new APK name
$newApkName = "${projectName}-v${versionName}-${suffix}-${buildDate}-${buildTime}.apk"
$destApk = Join-Path $outputDir $newApkName

# Copy and rename APK
Copy-Item $sourceApk $destApk -Force

$apkSize = (Get-Item $destApk).Length / 1MB

Write-Host ""
Write-Host "  APK saved to:" -ForegroundColor Green
Write-Host "  $destApk" -ForegroundColor Cyan
Write-Host ""
Write-Host "  File name: $newApkName" -ForegroundColor White
Write-Host "  File size: $([math]::Round($apkSize, 2)) MB" -ForegroundColor White
Write-Host ""
Write-Host "  ✅ APK已签名，可直接安装" -ForegroundColor Green
Write-Host "  🔐 使用开发签名: florisboard-dev.jks" -ForegroundColor Cyan
Write-Host ""
Write-Host "  💡 提示: 运行 查看签名信息.bat 可查看详细签名信息" -ForegroundColor Yellow

# ====================================
# Open output folder
# ====================================
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "All done!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Opening output folder..." -ForegroundColor Gray

Start-Sleep -Seconds 1

explorer.exe /select,"$destApk"

Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

